#include <REGX52.H>
#include "Timer.h"
#include "DS1302.h"

sbit DS1302_SCLK = P3^5;
sbit DS1302_IO   = P3^4;
sbit DS1302_CE   = P1^7;

unsigned char Time[7] = {55, 59, 23, 31, 12, 7, 25};   //{Second,Minute,Hour,Date,Month,Day,Year}

void DS1302_Init()
{
    DS1302_CE = 0;
    DS1302_SCLK = 0;
}

void DS1302_WriteByte(unsigned char Command,unsigned char Data)
{
    unsigned char i;
    Data = Data/10*16+Data%10;
    DS1302_CE = 1;
    for(i=0;i<8;i++)
    {
        DS1302_IO=(Command & (0x01<<i));
        DS1302_SCLK=1;
        DS1302_SCLK=0;
    }
    for (i = 0; i < 8; i++)
    {
        DS1302_IO = (Data & (0x01 << i));
        DS1302_SCLK = 1;
        DS1302_SCLK = 0;
    }
    DS1302_CE = 0;
}

unsigned char DS1302_ReadByte(unsigned char Command)
{
    unsigned char i, Data = 0x00;
    DS1302_CE = 1;
    for (i = 0; i < 8; i++)
    {
        DS1302_IO = (Command & (0x01 << i));
        DS1302_SCLK = 0;
        DS1302_SCLK = 1;
    }
    for(i=0;i<8;i++)
    {
        DS1302_SCLK=1;
        DS1302_SCLK=0;
        if(DS1302_IO)
        {
            Data|=(0x01<<i);
        }
    }
    DS1302_CE = 0;
    DS1302_IO=0;
    return (Data/16*10+Data%16);
}

void DS1302_SetTime()
{
    DS1302_WriteByte(DS1302_WP_W,0x00);
    DS1302_WriteByte(Second_W,Time[0]);
    DS1302_WriteByte(Minute_W,Time[1]);
    DS1302_WriteByte(Hour_W,Time[2]);
    DS1302_WriteByte(Date_W,Time[3]);
    DS1302_WriteByte(Month_W,Time[4]);
    DS1302_WriteByte(Day_W,Time[5]);
    DS1302_WriteByte(Year_W,Time[6]);
    DS1302_WriteByte(DS1302_WP_W,0x80);
}

void DS1302_ReadTime()
{
    Time[0]=DS1302_ReadByte(Second_R);
    Time[1] = DS1302_ReadByte(Minute_R);
    Time[2] = DS1302_ReadByte(Hour_R);
    Time[3] = DS1302_ReadByte(Date_R);
    Time[4] = DS1302_ReadByte(Month_R);
    Time[5] = DS1302_ReadByte(Day_R);
    Time[6] = DS1302_ReadByte(Year_R);
}